package com.nulldev.util.web.nTube.pages.invidious_compat;

import java.util.List;

import com.nulldev.util.JVM.JVM;
import com.nulldev.util.VariableAPI.MathUtil;
import com.nulldev.util.languages.json.uniapi.UniJsonValue;
import com.nulldev.util.web.HttpServer3.Response;
import com.nulldev.util.web.HttpServer3.pages.v3.HttpPage3;
import com.nulldev.util.web.YouTubeExtractor.metadata.YouTubeMetadata;
import com.nulldev.util.web.YouTubeExtractor.metadata.YouTubeMetadata.ThumbnailSizeOption;
import com.nulldev.util.web.YouTubeExtractor.trending.YouTubeTrending;
import com.nulldev.util.web.YouTubeExtractor.trending.YouTubeTrending.TrendingEntry;

public class APITrending extends HttpPage3 {

	public APITrending() {
		super("/api/v1/trending");
		this.setCachingMethod(CachingMethod.VERY_SHORT_CACHE);
		this.setChecks(EnhancedSecurityChecks.DISALLOW_POST_DATA, EnhancedSecurityChecks.ONLY_ALLOW_BASIC_METHODS);
	}

	@SuppressWarnings("resource")
	@Override
	public Response onRequest(final Request request) {
		final UniJsonValue v = UniJsonValue.array();
		final List<TrendingEntry> te;
		try {
			te = YouTubeTrending.getTrending();
		} catch (Exception ex) {
			JVM.errorln(ex);
			return new Response(200, v, v).setCustomMime("application/json");
		}
		for (final TrendingEntry entry : te) {
			final UniJsonValue e = UniJsonValue.object(15);
			e.add("title", entry.title);
			e.add("videoId", entry.videoID);
			final UniJsonValue videoThumbnails = UniJsonValue.array();
			for (int i = 0; i < ThumbnailSizeOption.MAX_RES_DEFAULT_WEBP.getLevel(); i++) {
				final UniJsonValue tee = UniJsonValue.object();
				final ThumbnailSizeOption sizeOption = ThumbnailSizeOption.fromLevel(i);
				final String url = YouTubeMetadata.ThumbnailSizeOption.getThumbnail(entry.videoID, sizeOption);
				tee.add("url", url);
				tee.add("quality", sizeOption.name());
				tee.add("width", sizeOption.width());
				tee.add("height", sizeOption.height());
				videoThumbnails.add(tee);
			}
			e.add("videoThumbnails", videoThumbnails);
			e.add("lengthSeconds", MathUtil.TimeToSeconds.parseTimeStringToSeconds(entry.durationText));
			e.add("viewCount", 0L);
			e.add("author", entry.channelName);
			e.add("authorId", "");
			e.add("authorUrl", entry.channelLink);
			e.add("published", -1L);
			e.add("publishedText", "N/A");
			e.add("description", "");
			e.add("descriptionHtml", "");
			e.add("liveNow", false);
			e.add("paid", false);
			e.add("premium", false);
			v.add(e);
		}
		return new Response(200, v, v).setCustomMime("application/json");
	}
}
